package com.lai.dao;

import com.lai.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: wlai
 * Date: 7/26/13
 * Time: 3:21 PM
 * To change this template use File | Settings | File Templates.
 */
@Component
public class JdbcUserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public List<User> listUsers() {
        List<User> list = jdbcTemplate.query("select * from users",new UserRowMapper() );
        return list;
    }

    public boolean validateLogin(String name, String password) {
        List l=jdbcTemplate.query("select * from users where name=? and password=?", new String[]{name, password}, new UserRowMapper());
        return l.size()>0;
    }

    public User getUserByUsername(String name){
        List<User> l=jdbcTemplate.query("select * from users where name=? ", new String[]{name}, new UserRowMapper());
        if(l.size()>0)return l.get(0);
        return null;
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("WEB-INF/applicationContext.xml");
        JdbcUserDao dao = (JdbcUserDao) context.getBean("jdbcUserDao");
        System.out.println(dao.validateLogin("lai","lai"));
    }
}

class UserRowMapper implements RowMapper {

    @Override
    public Object mapRow(ResultSet resultSet, int i) throws SQLException {
        User u = new User();
        u.setId(resultSet.getInt("id"));
        u.setName(resultSet.getString("name"));
        u.setPassword(resultSet.getString("password"));
        return u;
    }
}